<template>
  <section>
    <canvas ref="cav" class="border"></canvas>
  </section>
</template>

<script>
import {getRandomColor} from "@/utils/tools";

/**
 *@Description:画直线和虚线
 *@author ZY
 *@date 2022/11/20 21:38
 */
export default {
  name: "canvas-line",
  data() {
    return {}
  },
  mounted() {
    this.main()
  },
  methods: {
    main() {
      let that = this
      let lineCanvas = this.$refs.cav
      lineCanvas.height = 60
      let lineCtx = lineCanvas.getContext('2d')
      this.drawDashLine(lineCtx, [20, 20], 5, 6,)
      this.drawLine(lineCtx, 20, 40, 250, 40, 6, getRandomColor())

    },
    /**
     *@Description:虚线生成器
     *@author ZY
     *@date 2022/11/19 21:45
     *@param {Object} ctx canvas上下文
     *@param {Array} startPoint 起点X,Y坐标 [20,20]
     *@param {Number} dashPointLength 虚线每段长度 6
     *@param {Number} width 线条宽度
     */
    drawDashLine(ctx, startPoint = [20, 20], dashPointLength = 6, width) {
      for (let i = 0; i < 20; i++) {
        this.drawLine(ctx,
                i * 5 + startPoint[0],
                startPoint[1],
                i * 5 + startPoint[0] + dashPointLength,
                startPoint[1],
                width,
                getRandomColor())
        startPoint[0] += dashPointLength
      }
    },
    /**
     *@Description:直线生成器
     *@author ZY
     *@date 2022/11/19 21:45
     *@param {Object} ctx canvas上下文
     *@param {Number} x 起点X坐标
     *@param {Number} y 起点Y坐标
     *@param {Number} x1 终点X坐标
     *@param {Number} y1 终点Y坐标
     *@param {Number} width 线条宽度
     *@param {String} color 线条颜色
     */
    drawLine(ctx, x, y, x1, y1, width, color) {
      ctx.beginPath()
      ctx.moveTo(x, y)
      ctx.lineTo(x1, y1)
      ctx.strokeStyle = color
      ctx.lineWidth = width
      ctx.stroke()
      ctx.closePath()
    },
  }
}
</script>

<style lang="scss" scoped>
.border {
  border: 1px solid #dbdbdb;
  border-radius: 5px;
  overflow: hidden;
}
</style>
